import React, { useCallback, useEffect } from 'react';
import { View, Image, Text } from '@ray-js/components';
import { useActions, useProps } from '@ray-js/panel-sdk';

import CurtainDisplaySingle from '@/components/curtainDisplaySingle';
import { queryDps, getLaunchOptionsSync, useAppEvent } from '@ray-js/ray';

import Strings from '@/i18n';
import { Switch, Toast, ToastInstance, Icon } from '@ray-js/smart-ui';
import clsx from 'clsx';
import { useThrottleFn } from 'ahooks';
import warningIcon from '@tuya-miniapp/icons/dist/svg/Warning';
import { router } from '@ray-js/ray';
import { NavBarCustom } from '@/components/NavBarCustom';

import Slider2 from '@/components/Slider2';

import styles from './index.module.less';
import res from '../../../res';

function calculateBatteryBlocks(batteryPercentage) {
  const clampedPercentage = Math.max(0, Math.min(100, batteryPercentage));
  const number = Math.ceil(clampedPercentage / 25);

  return new Array(number).fill(0);
}

export default function Home() {
  const {
    control,
    percent_control,
    work_state,
    situation_set,
    sc_js: ScJs,
    percent_state,
    kc_fs: kcFs,
    battery_percentage: batteryPercentage,
    tyn,
    cd_zt: cdZt,
    fault,
    kc_sd: kcSd,
  } = useProps();
  console.log(`🚀 ~ percent_control:`, percent_control);

  const speed = (kcSd || 'level_1').slice(6, 7);

  useEffect(() => {
    if (fault) {
      ToastInstance({
        position: 'top',
        duration: 0,
      });
    } else {
      ToastInstance.clear();
    }
  }, [fault]);

  const actions = useActions();

  const onChangend = useCallback(
    e => {
      const nextPercent = e.detail.value.percent;
      actions.percent_control.set(nextPercent);
    },
    [percent_control]
  );

  const handleJump = useThrottleFn(
    (code: string) => {
      router.push(`/${code}`);
    },
    { wait: 80 }
  ).run;

  const btnList = ['open', 'stop', 'close'].map(item => ({
    name: Strings.getLang(item),
    icon: res[item],
    activeIcon: res[`${item}White`],
    value: item,
    onClick: () => {
      actions.control.set(item, {
        delay: 100,
      });
    },
  }));

  useAppEvent('onShow', () => {
    const {
      query: { deviceId },
    } = getLaunchOptionsSync();

    queryDps({
      deviceId,
      dpIds: ['1', '2', '3', '7', '12', '13', '119', '105'],
      success: res => {
        console.log('queryDps success', res);
      },
      fail: error => {
        console.log('queryDps fail', error);
      },
    });
  });


  const blockCount = calculateBatteryBlocks(batteryPercentage);

  return (
    <View className={styles.view}>
      <NavBarCustom />

      <View className={styles.chargeBox}>
        {tyn === 'on' ? <Image src={res.sunPower} className={styles.sunIcon} /> : null}
        <View className={styles.chargeContainer}>
          {cdZt === 'on' ? <Image src={res.charge} className={styles.chargeIcon} /> : null}
          <View className={styles.chargeBlockContainer}>
            {blockCount.map((item, index) => (
              // eslint-disable-next-line react/no-array-index-key
              <View
                key={index}
                className={clsx(
                  styles.chargeBlock,
                  batteryPercentage < 20 && styles.chargeBlockDanger
                )}
              />
            ))}
          </View>
        </View>
        <Text className={styles.chargeText}>{batteryPercentage}%</Text>
      </View>

      <View className={styles.curtainBox}>
        <View className={styles.windowbg}>
          <CurtainDisplaySingle
            dir={kcFs}
            control={control}
            value={percent_control}
            stateValue={percent_state}
            work_state={Strings.getLang(work_state)}
            speed={speed}
          />
        </View>
      </View>

      <View className={styles.bottomBox}>
        <View
          style={{
            width: `${336 * 2}rpx`,
            margin: '30rpx auto',
            position: 'relative',
            height: '140rpx',
          }}
        >
          <Slider2 // conflict
            control={control}
            leftValue={percent_control}
            bindchangend={onChangend}
            lock={false}
          />
        </View>

        <View className={styles.control}>
          {btnList.map(item => {
            const isActive = item.value === control;
            return (
              <View key={item.name} className={clsx(styles.controlItem)} onClick={item.onClick}>
                <View
                  className={clsx(
                    styles.controlItemIconBox,
                    isActive && styles.controlItemIconBoxActive
                  )}
                >
                  <Image
                    src={isActive ? item.activeIcon : item.icon}
                    className={styles.controlItemIcon}
                  />
                </View>
                <Text
                  className={clsx(styles.controlItemText, isActive && styles.controlItemTextActive)}
                >
                  {item.name}
                </Text>
              </View>
            );
          })}
        </View>

        <View className={styles.settingBox}>
          <View className={styles.lockBox}>
            <View className={styles.switchBox}>
              <Image src={ScJs ? res.lock : res.lockActive} className={styles.lock} />
              <Switch
                checked={ScJs}
                onChange={e => {
                  actions.sc_js.set(!ScJs);
                }}
                size="55rpx"
                activeColor="#40A1A7"
                inactiveColor="#D3E0DB"
                customClass={styles.switch}
              />
              <Image src={!ScJs ? res.unLock : res.unLockActive} className={styles.lock} />
            </View>

            <View className={styles.settingText}>
              <Text> {ScJs ? Strings.getLang('unlockWindow') : Strings.getLang('lockWindow')}</Text>
            </View>
          </View>

          <View
            className={styles.lockBox}
            onClick={() => {
              handleJump('Setting');
            }}
          >
            <View className={styles.switchBox}>
              <Image src={res.setting} className={styles.settingIcon} />
            </View>

            <View className={styles.settingText}>
              <Text>{Strings.getLang('setting')}</Text>
            </View>
          </View>
        </View>
      </View>
      <Toast id="smart-toast" duration={0}>
        <View className={styles.toast}>
          <Icon name={warningIcon} color="orange" size="16" className={styles.icon} />
          <Text>{Strings.getLang('motor_fault')}</Text>
        </View>
      </Toast>
    </View>
  );
}
